package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单模块定时任务相关代码
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    @Scheduled(cron = "0 0/1 * * * ? ")
    // @Scheduled(cron = "30 2 * * * ? ")// 测试可以临时设置一个触发比较快的时间点
    public void orderTimeout() {
        log.info("任务调度开始，清理超时订单。{}", LocalDateTime.now());
        // 1. 查询数据库，把超时的订单（状态必须是未支付，status = 1；下单时间跟现在时间差距超过15分钟）挑选出来
        // 计算当前时间的前15分钟是什么时刻，在这个时间点之前的订单，才会被计算为超时订单
        LocalDateTime orderTimeoutTime = LocalDateTime.now().minusMinutes(15);
        List<Orders> timeoutOrders = orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT, orderTimeoutTime);
        // 2. 把这些订单遍历，修改其状态为取消，同时设置取消原因
        if (!CollectionUtils.isEmpty(timeoutOrders)) {
            timeoutOrders.forEach(orders -> {
                // 取消每一个超时订单
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason(MessageConstant.ORDER_TIMEOUT);
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            });
        }
    }

    /**
     * 处理“派送中”状态的订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder() {
        log.info("处理派送中订单：{}", LocalDateTime.now());
        // select * from orders where status = 4 and order_time < 当前时间-1小时
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, time);

        if (!CollectionUtils.isEmpty(ordersList)) {
            ordersList.forEach(order -> {
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            });
        }
    }
}
